from django.db import models

# Create your models here.


class Device(models.Model):
    name = models.CharField(max_length=10,verbose_name="设备名称",unique=True)
    desc = models.CharField(max_length=200,verbose_name="设备描述")
    has_activated = models.BooleanField(default=True,verbose_name="是否激活")
    add_time = models.DateTimeField(auto_now_add=True,editable=True,verbose_name="添加时间")
    image = models.URLField(null=True,blank=True)
    def save(self,*args,**kwargs):
        if self.id is not None:
            import qrcode, os
            from users.models import SiteProfile
            from django.conf import settings
            qr = qrcode.QRCode(
                # version=1,
                # error_correction=qrcode.constants.ERROR_CORRECT_L,
                box_size=6,
                border=1,
            )
            site = SiteProfile.objects.get(pk=1)
            image_path = os.path.join(settings.MEDIA_ROOT, "device")
            url = "http://" + site.site.domain + ":" + str(site.port) + "/dev/" + str(self.id)
            qr.add_data(url)
            # img=qr.make(fit=True)

            img = qr.make_image()
            with open(os.path.join(image_path, str(self.id) + ".jpg"), 'wb') as f:
                img.save(f)
            img_url = "/media/device/" + str(self.id) + ".jpg"
            self.image=img_url
            super(Device,self).save(*args,**kwargs)
        else:
            super(Device,self).save(*args,**kwargs)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name="设备管理"
        verbose_name_plural=verbose_name

class DeviceStatus(models.Model):
    name = models.CharField(max_length=20,verbose_name="设备状态（10个汉字",unique=True)
    is_normal = models.BooleanField(default=False,verbose_name="是否正常")

    def __str__(self):
        return self.name

    class Meta:
        verbose_name="设备状态"
        verbose_name_plural=verbose_name
        ordering=("-is_normal",)


class DeviceBarcode(models.Model):
    device =models.OneToOneField(Device,related_name="rel_barcode_device")
    image = models.URLField()

